package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.UserInfo;

public class AddReviewProduct extends Activity implements OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	int PARAM_id = 0, PARAM_rating = 0;
	String url = "";
	EditText reviewText = null;
	RadioGroup ratingGroup = null;
	RadioButton ratingRadio1 = null, ratingRadio2 = null, ratingRadio3 = null, ratingRadio4 = null, ratingRadio5 = null;
	int rating = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_review_product);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		PARAM_id = fromIntent.getIntExtra("PARAM_id", 0);
		PARAM_rating = fromIntent.getIntExtra("PARAM_rating", 0);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ratingGroup = (RadioGroup) findViewById(R.id.ratingGroup);
		ratingRadio1 = (RadioButton) findViewById(R.id.ratingRadio1);
		ratingRadio2 = (RadioButton) findViewById(R.id.ratingRadio2);
		ratingRadio3 = (RadioButton) findViewById(R.id.ratingRadio3);
		ratingRadio4 = (RadioButton) findViewById(R.id.ratingRadio4);
		ratingRadio5 = (RadioButton) findViewById(R.id.ratingRadio5);
		ratingRadio1.setOnClickListener(this);
		ratingRadio2.setOnClickListener(this);
		ratingRadio3.setOnClickListener(this);
		ratingRadio4.setOnClickListener(this);
		ratingRadio5.setOnClickListener(this);
		
		switch (PARAM_rating) {
		case 1:
			ratingRadio1.setChecked(true);
			ratingRadio1.setBackgroundResource(R.drawable.rating_on1);
			break;
		case 2:
			ratingRadio2.setChecked(true);
			ratingRadio2.setBackgroundResource(R.drawable.rating_on2);
			break;
		case 3:
			ratingRadio3.setChecked(true);
			ratingRadio3.setBackgroundResource(R.drawable.rating_on3);
			break;
		case 4:
			ratingRadio4.setChecked(true);
			ratingRadio4.setBackgroundResource(R.drawable.rating_on4);
			break;
		case 5:
			ratingRadio5.setChecked(true);
			ratingRadio5.setBackgroundResource(R.drawable.rating_on5);
			break;
		}
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(this);
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("리뷰쓰기");
		
		reviewText = (EditText) findViewById(R.id.reviewText);
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(reviewText, InputMethodManager.SHOW_FORCED);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.okBt:
			String review = reviewText.getText().toString().trim();
			if (ratingGroup.getCheckedRadioButtonId() == R.id.ratingRadio1) {
				rating = 1;
			} else if (ratingGroup.getCheckedRadioButtonId() == R.id.ratingRadio2) {
				rating = 2;
			} else if (ratingGroup.getCheckedRadioButtonId() == R.id.ratingRadio3) {
				rating = 3;
			} else if (ratingGroup.getCheckedRadioButtonId() == R.id.ratingRadio4) {
				rating = 4;
			} else if (ratingGroup.getCheckedRadioButtonId() == R.id.ratingRadio5) {
				rating = 5;
			} else {
				Toast.makeText(this, "평점을 선택하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (review.equals("")) {
				Toast.makeText(this, "리뷰 내용을 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			url = getResources().getString(R.string.server_url) +  "/glowmee/addReviewProductXml.do?" +
					"idRegister=" + UserInfo.getInstance().getUSER_ID() + "&idProduct=" + PARAM_id + "&reviewText=" + review + "&rating=" + rating;
			
			(new AddWorker()).execute();
			break;
			
		case R.id.ratingRadio1:
			ratingRadio1.setBackgroundResource(R.drawable.rating_on1);
			ratingRadio2.setBackgroundResource(R.drawable.rating_off2);
			ratingRadio3.setBackgroundResource(R.drawable.rating_off3);
			ratingRadio4.setBackgroundResource(R.drawable.rating_off4);
			ratingRadio5.setBackgroundResource(R.drawable.rating_off5);
			break;
			
		case R.id.ratingRadio2:
			ratingRadio1.setBackgroundResource(R.drawable.rating_off1);
			ratingRadio2.setBackgroundResource(R.drawable.rating_on2);
			ratingRadio3.setBackgroundResource(R.drawable.rating_off3);
			ratingRadio4.setBackgroundResource(R.drawable.rating_off4);
			ratingRadio5.setBackgroundResource(R.drawable.rating_off5);
			break;
			
		case R.id.ratingRadio3:
			ratingRadio1.setBackgroundResource(R.drawable.rating_off1);
			ratingRadio2.setBackgroundResource(R.drawable.rating_off2);
			ratingRadio3.setBackgroundResource(R.drawable.rating_on3);
			ratingRadio4.setBackgroundResource(R.drawable.rating_off4);
			ratingRadio5.setBackgroundResource(R.drawable.rating_off5);
			break;
			
		case R.id.ratingRadio4:
			ratingRadio1.setBackgroundResource(R.drawable.rating_off1);
			ratingRadio2.setBackgroundResource(R.drawable.rating_off2);
			ratingRadio3.setBackgroundResource(R.drawable.rating_off3);
			ratingRadio4.setBackgroundResource(R.drawable.rating_on4);
			ratingRadio5.setBackgroundResource(R.drawable.rating_off5);
			break;
			
		case R.id.ratingRadio5:
			ratingRadio1.setBackgroundResource(R.drawable.rating_off1);
			ratingRadio2.setBackgroundResource(R.drawable.rating_off2);
			ratingRadio3.setBackgroundResource(R.drawable.rating_off3);
			ratingRadio4.setBackgroundResource(R.drawable.rating_off4);
			ratingRadio5.setBackgroundResource(R.drawable.rating_on5);
			break;
		}
	}
	
	public class AddWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(AddReviewProduct.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(AddReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("등록 성공");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						setResult(Activity.RESULT_OK, intent);
						finish();
					}
				});
				alert.create();
				alert.show();
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(AddReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("등록 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(AddReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new AddWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
    
}
